<template>
    <rx-layout>
        <div slot="left" width="250" showButton="true">
            <rx-fit>
                <a-directory-tree
                    class="rx-a-directory"
                    default-expand-all
                    :multiple="false"
                    :show-icon="true"
                    :treeData="catTreeData"
                    @select="selectCatTree">
                </a-directory-tree>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" @click="addAuthSetting">{{$ti18('rxList.newBtn','新建')}}
                        </a-button>
                        <a-dropdown>
                            <a-button style="margin-left: 8px"> {{$ti18('rxList.moreBtn','更多')}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="doImport"><i class="iconfont icondaoru"></i>{{$ti18('rxList.importBtn','导入')}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>{{$ti18('rxList.exportBtn','导出')}}</span>
                                    <a-menu-item @click="doExport('0')"><i class="iconfont icondaochu"></i>{{i18n('list.exportAll','导出当前所有')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('1')"><i class="iconfont icondaochu"></i>{{i18n('list.exportSel','导出所选中')}}
                                    </a-menu-item>
                                </a-sub-menu>
                                <a-menu-item
                                    key="2"
                                    @click="editOne"
                                    v-if="editEnable && selectedRowKeys.length > 0"
                                    alias="formRuleEdit"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn','编辑')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="3"
                                    @click="delByIds(selectedRowKeys)"
                                    v-if="removeEnable && selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'danger'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>{{$ti18('rxList.leachBtn','过滤')}}</span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.name','权限名称')">
                                    <a-input :placeholder="i18n('form.name','权限名称','input')"
                                             v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :bordered="isBorder"
                    :defaultPageSize="10"
                    url="/api-system/system/core/sysAuthSetting/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    @selectChange="onSelectChange"
                >

                    <span slot="name" slot-scope="{ text, record }">
                        {{$i18(text, '权限名称')}}
                    </span>
                    <span slot="category" slot-scope="{ text, record }" :title="getRightName(record)">
                          {{ getRightName(record) }}
                      </span>
                    <span slot="enable" slot-scope="{text,record,index}">
                       <a-tag :color="statusMap[text].color">
                        <span>{{statusMap[text].text}}</span>
                      </a-tag>
                    </span>
                    <span slot="action" slot-scope="{ text, record }" class="actionIcons">
            <span v-if="editEnable" @click.stop="editAuthSetting(record)">{{$ti18('rxList.editBtn','编辑')}}</span>
            <span v-if="removeEnable" @click.stop="delByIds([record.id])">{{$ti18('rxList.delBtn','删除')}}</span>
          </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
    import SysAuthSettingApi from '@/api/system/core/sysAuthSetting'
    import SysTreeCatApi from '@/api/system/core/sysTreeCat'
    import SysAuthSettingEdit from './SysAuthSettingEdit'
    import FormImport from '@/views/modules/form/core/FormImport'
    import {BaseList, Util} from "@lowcode/jpaas-common-lib";
    import {mapState} from 'vuex';
    import AppSearch from "@/views/modules/share/AppSearch";
    import RxSearchApp from "@/views/modules/share/rx-search-app";

    export default {
        name: 'SysAuthSettingList',
        mixins: [BaseList,AppSearch],
        components:{
            RxSearchApp
        },
        computed: {
            ...mapState({
                // 所属应用
                allApps: state => state.appSetting ? state.appSetting.allApps : {}
            }),
        },
        data() {
            return {
                columns: [
                    {
                        title: this.$ti18('rxList.index', '序号'),
                        type: 'indexColumn',
                        width: 60,
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'}
                    },
                    {
                        title: this.i18n('form.name', '权限名称'),
                        dataIndex: 'name', width: 100,
                        scopedSlots: {customRender: 'name'}},
                    {
                        title: this.i18n('form.enabled', '是否启用'),
                        dataIndex: 'enable',
                        scopedSlots: {customRender: 'enable'},
                        width: 100
                    },
                    {title: this.i18n('form.type', '类型'), dataIndex: 'type', width: 100},
                    {title: this.i18n('form.category', '分类'), dataIndex: 'category', width: 100,scopedSlots: {customRender: 'category'},},
                    {
                        title: this.$ti18('rxForm.createTime', '创建时间'),
                        dataIndex: 'createTime',
                        sorter: true,
                        sortField: 'CREATE_TIME_',
                        width: 150
                    },
                    {
                        title: this.$ti18('rxList.action', '操作'),
                        width: 80,
                        dataIndex: 'action',
                        scopedSlots: {customRender: 'action'}
                    }
                ],
                component: SysAuthSettingEdit,
                comment: this.i18n('list.comment', '权限配置表'),
                widthHeight: ['800px', '600px'],
                catTreeData: [],
                statusMap: {
                    "true": {color: 'green', text: this.i18n('form.enable', '启用')},
                    "false": {color: 'red', text: this.i18n('form.disable', '停用')}
                },
                catKey: "",

            }
        },
        created() {
            this.loadCatTree();
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "SysAuthSetting", key);
            },
            getRightName(record){
                if (!record.sysAuthRights){
                    return ""
                }
                var sysAuthRights=record.sysAuthRights;
                var rightName="";
                for (let sysAuthRight of sysAuthRights){
                    rightName+=this.$i18(sysAuthRight.treeName)+","
                }
                //去除最后的 ，
                rightName=(rightName.length>0?rightName.substring(0,rightName.length-1):"")
                return rightName;
            },
            loadCatTree() {
                let self_ = this;
                SysTreeCatApi.getCatList().then(resp => {
                    let data = resp;
                    for (let i = 0; i < data.length; i++) {
                        var rs = data[i];
                        if (rs.key=="APP"){
                            continue
                        }
                        this.catTreeData.push({title: self_.$i18(rs.name, '分类名称'), catId: rs.catId, key: rs.key})
                    }
                })
            },
            delById(ids) {
                return SysAuthSettingApi.del({ids: ids.join(',')});
            },
            getListByParams(parameter) {
                return SysAuthSettingApi.query(parameter)
            },
            selectCatTree(selKeys, e) {
                if (selKeys.length == 0) {
                    delete this.queryParam.Q_TYPE__S_EQ;
                } else {
                    this.catKey = selKeys[0];
                    this.queryParam.Q_TYPE__S_EQ = this.catKey;
                }
                this.$refs.table.loadData();
            },
            editOneAuthSetting() {
                var conf = {
                    component: this.component,
                    title: this.i18n('list.editTitle', '编辑') + this.comment,
                    widthHeight: this.widthHeight
                };
                if (this.selectedRows.length > 0) {
                    conf.pkId = this.selectedRows[0].pkId;
                    conf.data = {pkId: conf.pkId, type: this.selectedRows[0].type};
                    this.handleEdit(conf)
                }
            },
            editAuthSetting(record) {
                var conf = {
                    pkId: record.pkId,
                    component: this.component,
                    title: this.i18n('list.editTitle', '编辑') + this.comment,
                    widthHeight: this.widthHeight,
                    data: {pkId: record.pkId, type: record.type}
                };
                this.handleEdit(conf);
            },
            addAuthSetting() {
                if (!this.queryParam.Q_TYPE__S_EQ) {
                    this.$message.error(this.i18n('msa.selectTips', '请选择分类树！'));
                    return;
                }
                var self_ = this;
                var conf = {
                    component: this.component,
                    title: this.i18n('list.addTitle', '添加') + this.comment,
                    widthHeight: this.widthHeight,
                    "curVm": self_,
                    "data": {"type": this.queryParam.Q_TYPE__S_EQ}
                };
                Util.open(conf, function (action) {
                    if (action == "ok") {
                        self_.refreshGrid();
                    }
                });
            },
            search() {
                this.$refs.table.loadData();
            },
            cancel() {
                this.resetSearch();
            },
            closeSearchbar() {
                //关闭过滤弹窗；（点击X触发）
                this.fitSearch = false;
            },

            doExport(isSelected) {
                var exportList = [];
                if (isSelected == "1") {
                    exportList = this.$refs.table.getSelectedRows();
                    if (!exportList || exportList.length == 0) {
                        this.$warning({
                            title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                            content: this.i18n('msa.exportTips', '请选择需要导出的记录！'),
                        });
                        return;
                    }
                } else {
                    exportList = this.$refs.table.dataAction;
                }

                if (exportList == "") {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                        content: this.i18n('msa.exportError', '该分类没有数据！'),
                    });
                    return;
                }

                var solutionIds = []
                exportList.forEach((item) => {
                    solutionIds.push(item.id)
                })
                SysAuthSettingApi.doExport(solutionIds)
            },

            doImport() {
                if (!this.catKey) {
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                        content: this.i18n('msa.importTips', '请选择系统授权的分类！'),
                    });
                    return
                }
                var treeId = this.catKey
                Util.open(
                    {
                        component: FormImport,
                        curVm: this,
                        widthHeight: ['800px', '600px'],
                        title: this.i18n('list.importTiTle', '授权分类导入'),
                        data: {
                            treeId: treeId,
                            callback: function (params) {
                                let self = this;
                                SysAuthSettingApi.doImport(params).then(res => {
                                    this.isSpinning = false;
                                    if (!res.success) {
                                        self.$confirm({
                                            title: self.$ti18('rxMsa.masWarn.delInfo', '警告'),
                                            content: self.$ti18('msa.importError', '导入失败！', "SysAuthSetting"),
                                            okText: self.$ti18('rxForm.ackBtn', '确认'),
                                            cancelText: self.$ti18('rxForm.cancelBtn', '取消'),
                                        });
                                        return;
                                    }
                                    self.getUpdataSqls(res.data);
                                });
                            }
                        }
                    }, function (action) {
                    });
            },
        }
    }
</script>
<style scoped>
.rx-a-directory >>> .ant-tree-switcher-noop{
    display: none;
}
</style>

